﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wintellect.Sterling;
using dIRca.Data.Settings;

namespace dIRca.Data.Services
{
    public class DatabaseService : IDisposable
    {
        public const long KILOBYTE = 1024;
        public const long MEGABYTE = 1024 * KILOBYTE;
        public const long QUOTA = 100 * MEGABYTE;

        private SterlingEngine _engine;
        private Guid _loggerId;
        private SterlingDefaultLogger _logger;

        public static DatabaseService Current { get; private set; }
        public ISterlingDatabaseInstance Database { get; private set; }
        public bool IsRunning { get; private set; }

        public event EventHandler RebuildRequested;

        public void Start()
        {
            _engine = new SterlingEngine();
            Current = this;
        }

        public void Starting()
        {
            //_loggerId =
            //   _engine.SterlingDatabase.RegisterLogger(
            //       (level, message, exception) => ExecuteOnUIThread(() => Logger.SetMessage(level, message, exception)));

            _logger = new SterlingDefaultLogger(SterlingLogLevel.Verbose);
            //_engine.SterlingDatabase.RegisterSerializer<FoodSerializer>();

            _engine.Activate();
            Database = _engine.SterlingDatabase.RegisterDatabase<ModelDatabase>();
            Database.RegisterTrigger(new IdentityTrigger<LastConnection>(Database));
            IsRunning = true;
        }

        public void Stop()
        {
            return;
        }

        public void Exiting()
        {
            //_engine.SterlingDatabase.UnhookLogger(_loggerId);
            if (_logger != null)
                _logger.Detach();
        }

        public void Exited()
        {
            Dispose();
            _engine = null;
            IsRunning = false;
            return;
        }

        public void RequestRebuild()
        {
            if (RebuildRequested != null)
            {
                RebuildRequested(this, EventArgs.Empty);
            }
        }

        public void Dispose()
        {
            if (_engine != null)
            {
                _engine.Dispose();
            }
            GC.SuppressFinalize(this);
        }
    }
}
